package com.yangjiangtao.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        // 创建session
        HttpSession session = httpRequest.getSession();
        // 获取路径
        String requestURL = httpRequest.getRequestURL().toString();

        // 如果请求页面为登录页面，则直接放行
        if(requestURL.endsWith("/login.jsp")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        // 如果请求页面为main.jsp,则查看session是否已经建立
        if(requestURL.endsWith("/main.jsp")){
            Boolean flag = (Boolean) session.getAttribute("flag");
            if(flag != null && flag){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }else{
                //重定向到login.jsp
                httpResponse.sendRedirect("/login.jsp");
            }
        }

        // 如果当前请求路径为MainServlet，则拦截
        if(requestURL.endsWith("/MainServlet")){
            // 获取请求登录的用户名和密码
            String name = httpRequest.getParameter("name");
            String password = httpRequest.getParameter("password");
            // 如果请求的参数正确，则放行并设置flag为true
            if ("admin".equals(name) && "123456".equals(password)) {
                // 设置session的属性
                session.setAttribute("flag",true);
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }else{
                //不正确则重定向到login.jsp
                httpResponse.sendRedirect("/login.jsp");
            }
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
}
